/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web.UI;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Web.UI.DataVisualization.Charting;
using System.Collections.Generic;
using NS_Controls;

public partial class ServiceUsing : SessionPageBase
{
    private static string sql = "SelectUsingServices", sessionKey = "ds_" + sql;
	private static string chartTitle = "Indicatori Utilizare Servicii";

    protected void Page_Load(object sender, EventArgs e)
    {
		try
        {
			SetEventHandlers();
			if (!IsPostBack)
            {
                txtStartDate.Text = System.DateTime.Now.ToShortDateString();
                txtEndDate.Text = System.DateTime.Now.ToShortDateString();

                ClearSession(sessionKey);
                Load_Data(false);
				ddlSelectAllDiagrame.SelectedValue = "Pie";
				ddlSelectAllDiagrame_SelectedIndexChanged(null, null);
			}
			else
				RebuildCharts();
		}
        catch (Exception ex)
        {
			output.Text = "<!--" + ex.ToString() + "-->";
			this.Master.SetMessage(ex.Message, true);
        }
    }

	private void SetEventHandlers()
	{
		foreach (ExtendedGridView gr in new ExtendedGridView[] { grPacExtern, grDurata, grRataPat, grPropPac, grPacAmb, grPropUrg, grDurataUPU, grNrServicii, grIndCom, grProcPacInterv, grProcComp, grNrPacSec })
		{
			gr.DataSourceChanged += new EventHandler(ExtGridView_DataSourceChanged);
			gr.PageIndexChanged += new EventHandler(ExtGridView_DataSourceChanged);
		}
	}

    private void ExtGridView_DataSourceChanged(object sender, EventArgs e)
    {
        ExtendedGridView source = sender as ExtendedGridView;
        System.Web.UI.DataVisualization.Charting.Chart c = source.Parent.FindControl(source.ID.Replace("gr", "chart")) as System.Web.UI.DataVisualization.Charting.Chart;
        DropDownList ddl = null;

        foreach (Control child in source.Parent.Controls) if (child is DropDownList) ddl = child as DropDownList;
        if (c != null)
            BuildChart(c, source, ddl.SelectedValue);
    }

    private void Load_Data(bool bForce)
    {
        try
        {
            string[] chartTypes = GetChartTypes();
            ddlSelectAllDiagrame.DataSource = chartTypes;
            ddlSelectAllDiagrame.DataBind();

			DataTable dtActiveTabs = Hipocrate.DB.DBConnection.GetData("SELECT TabCode, Active FROM Doc_Type_Tabs WHERE page = 'SU' OR page IS NULL").Tables[0];
			System.Collections.Generic.Dictionary<string, bool> active = new System.Collections.Generic.Dictionary<string, bool>();
			foreach (DataRow tab in dtActiveTabs.Rows)
				active[tab["TabCode"].ToString()] = System.Convert.ToBoolean(tab["Active"]);

			int nrCrt = 0;

			if (tab1.Visible = active["PacExtern"]) //assignment is on purpose
			{
				Load_Grid(grPacExtern, 0, bForce);
				ddlSelectDiagram1.DataSource = chartTypes;
				ddlSelectDiagram1.DataBind();
				//SetTabHeaderPrefix(tab1, ++nrCrt);
			}

			if (tab2.Visible = active["Durata"]) //assignment is on purpose
			{
				Load_Grid(grDurata, 1, bForce);
				ddlSelectDiagram2.DataSource = chartTypes;
				ddlSelectDiagram2.DataBind();
				//SetTabHeaderPrefix(tab2, ++nrCrt);
			}

			if (tab3.Visible = active["RataPat"]) //assignment is on purpose
			{
				Load_Grid(grRataPat, 2, bForce);
				ddlSelectDiagram3.DataSource = chartTypes;
				ddlSelectDiagram3.DataBind();
				//SetTabHeaderPrefix(tab3, ++nrCrt);
			}

			if (tab4.Visible = active["PropPac"]) //assignment is on purpose
			{
				Load_Grid(grPropPac, 3, bForce);
				ddlSelectDiagram4.DataSource = chartTypes;
				ddlSelectDiagram4.DataBind();
				//SetTabHeaderPrefix(tab4, ++nrCrt);
			}

			if (tab5.Visible = active["PacAmb"]) //assignment is on purpose
			{
				Load_Grid(grPacAmb, 4, bForce);
				ddlSelectDiagram5.DataSource = chartTypes;
				ddlSelectDiagram5.DataBind();
				//SetTabHeaderPrefix(tab5, ++nrCrt);
			}

			if (tab6.Visible = active["PropUrg"]) //assignment is on purpose
			{
				Load_Grid(grPropUrg, 5, bForce);
				ddlSelectDiagram6.DataSource = chartTypes;
				ddlSelectDiagram6.DataBind();
				//SetTabHeaderPrefix(tab6, ++nrCrt);
			}

			if (tab7.Visible = active["DurataUPU"]) //assignment is on purpose
			{
				Load_Grid(grDurataUPU, 6, bForce);
				ddlSelectDiagram7.DataSource = chartTypes;
				ddlSelectDiagram7.DataBind();
				//SetTabHeaderPrefix(tab7, ++nrCrt);
			}

			if (tab8.Visible = active["NrServicii"]) //assignment is on purpose
			{
				Load_Grid(grNrServicii, 7, bForce);
				ddlSelectDiagram8.DataSource = chartTypes;
				ddlSelectDiagram8.DataBind();
				//SetTabHeaderPrefix(tab8, ++nrCrt);
			}

			if (tab9.Visible = active["IndCom"]) //assignment is on purpose
			{
				Load_Grid(grIndCom, 8, bForce);
				ddlSelectDiagram9.DataSource = chartTypes;
				ddlSelectDiagram9.DataBind();
				//SetTabHeaderPrefix(tab9, ++nrCrt);
			}

			if (tab10.Visible = active["ProcPacInterv"]) //assignment is on purpose
			{
				Load_Grid(grProcPacInterv, 9, bForce);
				ddlSelectDiagram10.DataSource = chartTypes;
				ddlSelectDiagram10.DataBind();
				//SetTabHeaderPrefix(tab10, ++nrCrt);
			}

			if (tab11.Visible = active["ProcComp"]) //assignment is on purpose
			{
				Load_Grid(grProcComp, 10, bForce);
				ddlSelectDiagram11.DataSource = chartTypes;
				ddlSelectDiagram11.DataBind();
				//SetTabHeaderPrefix(tab11, ++nrCrt);
			}

			if (tab12.Visible = active["NrPacSec"]) //assignment is on purpose
			{
				Load_Grid(grNrPacSec, 11, bForce);
				ddlSelectDiagram12.DataSource = chartTypes;
				ddlSelectDiagram12.DataBind();
				//SetTabHeaderPrefix(tab12, ++nrCrt);
			}
        }

        catch (Exception ex)
        {
			output.Text = "<!--" + ex.ToString() + "-->";
			this.Master.SetMessage(ex.Message, true);
        }
    }
    protected void ddlSelectAllDiagrame_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selectedValue = ddlSelectAllDiagrame.SelectedValue;
		foreach (DropDownList ddl in new DropDownList[] { ddlSelectDiagram1, ddlSelectDiagram2, ddlSelectDiagram3, ddlSelectDiagram4, ddlSelectDiagram5, ddlSelectDiagram6, ddlSelectDiagram7, ddlSelectDiagram8, ddlSelectDiagram9, ddlSelectDiagram10, ddlSelectDiagram11, ddlSelectDiagram12 })
		{
			ddl.SelectedValue = selectedValue;
			ddlSelectSpecificDiagram(ddl, null);
		}
    }

    protected void ddlSelectSpecificDiagram(object sender, EventArgs e)
    {
        DropDownList ddl = sender as DropDownList;
        if (ddl == null) return;

		SeriesChartType selectedType;
		try
		{
			selectedType = GetChartType(ddl.SelectedValue);
		}
		catch (ArgumentException) //Must specify valid information for parsing in the string.
		{
			return;
		}
        Chart chart = null;

        foreach (Control c in ddl.Parent.Controls)
            if (c is System.Web.UI.DataVisualization.Charting.Chart)
            {
                chart = c as System.Web.UI.DataVisualization.Charting.Chart;
                foreach (System.Web.UI.DataVisualization.Charting.Series s in chart.Series)
                    s.ChartType = selectedType;
				break; //only set the type for the first chart, if there are more
            }
    }

    private string[] GetChartTypes()
    {
        object[] fields = typeof(System.Web.UI.DataVisualization.Charting.SeriesChartType).GetFields();
        List<string> result = new List<string>(fields.Length);
        foreach (System.Reflection.FieldInfo fi in fields)
            if (fi.IsStatic)
                result.Add(fi.Name);
        result.Sort();
		//remove the useless ones:
        result.Remove("PointAndFigure");
        result.Remove("StackedArea100");
        result.Remove("StackedBar100");
        result.Remove("StackedColumn100");
        result.Remove("ThreeLineBreak");

		//second approach: white-list!
		result.Clear();
        result.Add("Area");
        result.Add("Bar");
        result.Add("Column");
        result.Add("Doughnut");
        result.Add("Pie");
        result.Add("Range");
        result.Add("Spline");
        result.Add("SplineArea");
        result.Add("SplineRange");
        result.Add("StackedArea");
        return result.ToArray();
    }

    private void Load_Grid(ExtendedGridView target, int tableIndex, bool bForceReload)
    {
        DataSet fullBundle = GetSession(sessionKey) as DataSet;
		#region rebuild DataSet
		if (fullBundle == null || bForceReload)
		{
			fullBundle = BuildSessionDataSet(sessionKey, sql, new string[] { "StartDate", "EndDate" }, new object[] { CommonSession.StareDiagramaIndicatori.GetDate(txtStartDate), CommonSession.StareDiagramaIndicatori.GetDate(txtEndDate) });
			//add column for percentage:
			foreach (DataTable dt in fullBundle.Tables)
			{
				dt.Columns.Add("Percentage");
				decimal sum = 0;
				foreach (DataRow dr in dt.Rows)
					sum += System.Convert.ToDecimal(dr["nrExtern"]);

				foreach (DataRow dr in dt.Rows)
				{
					decimal currentValue = System.Convert.ToDecimal(dr["nrExtern"]);
					dr["Percentage"] = (currentValue == 0 ? 0 : System.Convert.ToInt32(100 * currentValue / sum));
				}
			}

			SetSession(sessionKey, fullBundle);
		}
		#endregion
		if (fullBundle != null && (bForceReload || !IsPostBack))
        {
            DataTable data = fullBundle.Tables[tableIndex];

            target.SessionKey = GetSessionKey(sessionKey);
            target.SessionKeyIndex = tableIndex;
            target.SessionKeyFilter = "";
            target.DataSource = data.DefaultView;
            target.DataBind();
        }
    }

    private void RebuildCharts()
    {
        DataSet fullBundle = GetSession(sessionKey) as DataSet;

        if (fullBundle == null)
            return;

        BuildChart(chartPacExtern, grPacExtern, ddlSelectDiagram1.SelectedValue);
        BuildChart(chartDurata, grDurata, ddlSelectDiagram2.SelectedValue);
        BuildChart(chartRataPat, grRataPat, ddlSelectDiagram3.SelectedValue);
        BuildChart(chartPropPac, grPropPac, ddlSelectDiagram4.SelectedValue);
        BuildChart(chartPacAmb, grPacAmb, ddlSelectDiagram5.SelectedValue);
        BuildChart(chartPropUrg, grPropUrg, ddlSelectDiagram6.SelectedValue);
        BuildChart(chartDurataUPU, grDurataUPU, ddlSelectDiagram7.SelectedValue);
        BuildChart(chartNrServicii, grNrServicii, ddlSelectDiagram8.SelectedValue);
        BuildChart(chartIndCom, grIndCom, ddlSelectDiagram9.SelectedValue);
        BuildChart(chartProcPacInterv, grProcPacInterv, ddlSelectDiagram10.SelectedValue);
        BuildChart(chartProcComp, grProcComp, ddlSelectDiagram11.SelectedValue);
        BuildChart(chartNrPacSec, grNrPacSec, ddlSelectDiagram12.SelectedValue);
    }

    private void BuildChart(System.Web.UI.DataVisualization.Charting.Chart target, ExtendedGridView data, string chartType)
    {
		if (data.DataSource == null)
		{
			target.Titles[0].Text = "No data"; //a bit useless, since it's within a tab that will not be shown...
			return;
		}
		if (!target.Titles[0].Text.Equals(chartTitle))
		{
			Tools.ScrieInLog(Server, "Chart title for '" + target.ID + "' was '" + target.Titles[0].Text + "' instead of '" + chartTitle + "'.");
			target.Titles[0].Text = chartTitle;
		}
		target.Series.Clear();
        target.Series.Add("Procentaj");
        if (!string.IsNullOrEmpty(chartType))
            target.Series[0].ChartType = GetChartType(chartType);

		decimal sum = 0;
		foreach (DataRowView rv in data.DataSource)
			sum += System.Convert.ToDecimal(rv["nrExtern"]);

        int pgOffset = data.PageSize * data.PageIndex;
		while ((data.DataSource.Count <= pgOffset) && (pgOffset > 0))
			pgOffset -= data.PageSize;

        decimal runningTotal = 0;
		int nRowCount = data.PageSize;
		if (nRowCount < 0)
		{
			nRowCount = data.DataSource.Count;
			pgOffset = 0;
		}
		for (int i = 0; i < nRowCount; ++i)
			if ((i + pgOffset) < data.DataSource.Count)
			{
                DataRowView dr = data.DataSource[i + pgOffset];
				runningTotal += System.Convert.ToDecimal(dr["nrExtern"]);
				target.Series[0].Points.AddXY(dr["Percentage"].ToString() + "%", dr["nrExtern"]);
				target.Series[0].Points[target.Series[0].Points.Count - 1].LegendText = dr["ID"].ToString();
            }
		//target.Series[0].Points.AddXY(System.Convert.ToInt32(100 * (sum - runningTotal) / sum).ToString() + "%", sum - runningTotal);
		//target.Series[0].Points[target.Series[0].Points.Count - 1].LegendText = "other";
	}

    private System.Web.UI.DataVisualization.Charting.SeriesChartType GetChartType(string chartType)
    {
        return (System.Web.UI.DataVisualization.Charting.SeriesChartType)Enum.Parse(typeof(System.Web.UI.DataVisualization.Charting.SeriesChartType), chartType);
    }

    protected void btn_Load(object sender, EventArgs e)
    {
        try
        {
            Load_Data(true);
        }
        catch (Exception ex)
        {
			output.Text = "<!--" + ex.ToString() + "-->";
			this.Master.SetMessage(ex.Message, true);
        }
    }

	#region Print Preview
	protected void btnPreview1_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grPacExtern, tab1, 0, ddlSelectDiagram1), true);
	}
	protected void btnPreview2_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grDurata, tab2, 1, ddlSelectDiagram2), true);
	}
	protected void btnPreview3_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grRataPat, tab3, 2, ddlSelectDiagram3), true);
	}
	protected void btnPreview4_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grPropPac, tab4, 3, ddlSelectDiagram4), true);
	}
	protected void btnPreview5_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grPacAmb, tab5, 4, ddlSelectDiagram5), true);
	}
	protected void btnPreview6_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grPropUrg, tab6, 5, ddlSelectDiagram6), true);
	}
	protected void btnPreview7_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grDurataUPU, tab7, 6, ddlSelectDiagram7), true);
	}
	protected void btnPreview8_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grNrServicii, tab8, 7, ddlSelectDiagram8), true);
	}
	protected void btnPreview9_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grIndCom, tab9, 8, ddlSelectDiagram9), true);
	}
	protected void btnPreview10_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grProcPacInterv, tab10, 9, ddlSelectDiagram10), true);
	}
	protected void btnPreview11_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grProcComp, tab11, 10, ddlSelectDiagram11), true);
	}
	protected void btnPreview12_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grNrPacSec, tab12, 11, ddlSelectDiagram12), true);
	}

	private string GetGuid(ExtendedGridView gv, AjaxControlToolkit.TabPanel t, int i, DropDownList ddl)
	{
		return CommonSession.SetStareDiagramaIndicatori(this, chartTitle, t.HeaderTemplate, sql, txtStartDate, txtEndDate,
			i, gv.PageSize, gv.PageIndex, gv.GetRowFilter(), gv.GridViewSortExpression, gv.GridViewSortDirection, gv.Columns, ddl.SelectedValue);
	}
	#endregion
}
